package com.sangshen.ad_suyi_flutter_sdk;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.admobiletop.adsuyi.ad.ADSuyiSplashAd;
import cn.admobiletop.adsuyi.ad.data.ADSuyiAdInfo;
import cn.admobiletop.adsuyi.ad.entity.ADSuyiAdSize;
import cn.admobiletop.adsuyi.ad.entity.ADSuyiExtraParams;
import cn.admobiletop.adsuyi.ad.error.ADSuyiError;
import cn.admobiletop.adsuyi.ad.listener.ADSuyiSplashAdListener;
import io.flutter.embedding.android.FlutterActivity;
import com.sangshen.ad_suyi_flutter_sdk.util.SPUtil;
import com.sangshen.ad_suyi_flutter_sdk.util.UIUtils;

/**
 * @author ciba
 * @description 开屏广告示例，开屏广告容器请保证有屏幕高度的75%，建议开屏界面设置为全屏模式并禁止返回按钮
 * @date 2020/3/25
 */
public class SplashAdActivity extends FlutterActivity {
    private static AdInstanceManager adInstanceManager;

    private static final String AD_ID_KEY = "AD_ID_KEY";
    private static final String AD_POS_ID_KEY = "AD_POS_ID_KEY";
    private static final String IMG_NAME_KEY = "IMG_NAME_KEY";
    private static final String IMG_LOGO_NAME_KEY = "IMG_LOGO_NAME_KEY";
    private static final String IS_REPEAT_APPLY_PERMISSION = "IS_REPEAT_APPLY_PERMISSION";
    private static final String IS_APPLY_PERMISSION = "IS_APPLY_PERMISSION";

    private int adId;
    private String adPosId;
    private String imgName;
    private String imgLogoName;
    private boolean isRepeatApplyPermission;
    private boolean isApplyPermission;

    /**
     * 根据实际情况申请
     */
    private static final String[] PERMISSIONS = {Manifest.permission.READ_PHONE_STATE
            , Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.ACCESS_COARSE_LOCATION
            , Manifest.permission.ACCESS_FINE_LOCATION
    };
    private static final int REQUEST_CODE = 7722;

    private List<String> permissionList = new ArrayList<>();
    private ADSuyiSplashAd adSuyiSplashAd;

    private LinearLayout rlBackground;
    private FrameLayout flContainer;
    private LinearLayout llLogoContainer;
    private ImageView ivLogo;

    public static void startActivity(
            Context context,
            AdInstanceManager manager,
            int adId,
            String adPosId,
            String imgName,
            String imgLogoName,
            boolean isRepeatApplyPermission,
            boolean isApplyPermission
    ) {
        adInstanceManager = manager;
        Intent intent = new Intent(context, SplashAdActivity.class);
        intent.putExtra(AD_ID_KEY, adId);
        intent.putExtra(AD_POS_ID_KEY, adPosId);
        intent.putExtra(IMG_NAME_KEY, imgName);
        intent.putExtra(IMG_LOGO_NAME_KEY, imgLogoName);
        intent.putExtra(IS_REPEAT_APPLY_PERMISSION, isRepeatApplyPermission);
        intent.putExtra(IS_APPLY_PERMISSION, isApplyPermission);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent != null) {
            adId = intent.getIntExtra(AD_ID_KEY, -1);
            adPosId = intent.getStringExtra(AD_POS_ID_KEY);
            imgName = intent.getStringExtra(IMG_NAME_KEY);
            imgLogoName = intent.getStringExtra(IMG_LOGO_NAME_KEY);
            isRepeatApplyPermission = intent.getBooleanExtra(IS_REPEAT_APPLY_PERMISSION, false);
            isApplyPermission = intent.getBooleanExtra(IS_APPLY_PERMISSION, false);
        }

        setContentView(R.layout.activity_splash_ad);
        rlBackground = findViewById(R.id.rlBackground);
        flContainer = findViewById(R.id.flContainer);
        llLogoContainer = findViewById(R.id.llLogoContainer);
        ivLogo = findViewById(R.id.ivLogo);

        if (!TextUtils.isEmpty(imgName)) {
            //得到application对象
            ApplicationInfo appInfo = getApplicationInfo();
            //得到该图片的id(name 是该图片的名字，"drawable" 是该图片存放的目录，appInfo.packageName是应用程序的包)
            int resID = getResources().getIdentifier(imgName, "drawable", appInfo.packageName);
            if (resID != 0) {
                rlBackground.setBackgroundResource(resID);
            }
        }

        if (!TextUtils.isEmpty(imgLogoName)) {
            llLogoContainer.setVisibility(View.VISIBLE);
            //得到application对象
            ApplicationInfo appInfo = getApplicationInfo();
            //得到该图片的id(name 是该图片的名字，"drawable" 是该图片存放的目录，appInfo.packageName是应用程序的包)
            int dID = getResources().getIdentifier(imgLogoName, "drawable", appInfo.packageName);
            int mID = getResources().getIdentifier(imgLogoName, "mipmap", appInfo.packageName);
            if (dID != 0) {
                ivLogo.setImageResource(dID);
            } else if (mID != 0) {
                ivLogo.setImageResource(mID);
            }
        }

        checkPrivacyPolicy();
    }

    /**
     * 检查隐私政策
     */
    private void checkPrivacyPolicy() {
        // 如果同意了则直接初始化广告SDK并加载开屏广告
        initADSuyiSdkAndLoadSplashAd();
    }

    /**
     * 初始化广告SDK并且跳转开屏界面
     */
    private void initADSuyiSdkAndLoadSplashAd() {
        initSplashAd();
    }

    private void initSplashAd() {
        // 6.0及以上获取没有申请的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : PERMISSIONS) {
                int checkSelfPermission = ContextCompat.checkSelfPermission(this, permission);
                if (PackageManager.PERMISSION_GRANTED == checkSelfPermission) {
                    continue;
                }
                permissionList.add(permission);
            }
        }

        // 创建开屏广告实例，第一个参数可以是Activity或Fragment，第二个参数是广告容器（请保证容器不会拦截点击、触摸等事件，高度不小于真实屏幕高度的75%，并且处于可见状态）
        adSuyiSplashAd = new ADSuyiSplashAd(this, flContainer);
        // 屏幕宽度px
        int widthPixels = UIUtils.getScreenWidthInPx(this);
        // 屏幕高度px
        int heightPixels = UIUtils.getScreenHeightInPx(this);

        if (!TextUtils.isEmpty(imgLogoName)) {
            int logoHeight = UIUtils.dp2px(this, 100);
            heightPixels = heightPixels - logoHeight;

            ViewGroup.LayoutParams layoutParams = llLogoContainer.getLayoutParams();
            layoutParams.height = logoHeight;
            llLogoContainer.setLayoutParams(layoutParams);
        }

        // 创建额外参数实例
        ADSuyiExtraParams extraParams = new ADSuyiExtraParams.Builder()
                // 设置整个广告视图预期宽高(目前仅头条平台需要，没有接入头条可不设置)，单位为px，如果不设置头条开屏广告视图将会以9 : 16的比例进行填充，小屏幕手机可能会出现素材被压缩的情况
                .adSize(new ADSuyiAdSize(widthPixels, heightPixels))
                .build();
        // 如果开屏容器不是全屏可以设置额外参数
        adSuyiSplashAd.setLocalExtraParams(extraParams);
        // 设置是否是沉浸式，如果为true，跳过按钮距离顶部的高度会加上状态栏高度
        // 设置仅支持的广告平台，设置了这个值，获取广告时只会去获取该平台的广告，null或空字符串为不限制，默认为null，方便调试使用，上线时建议不设置
        adSuyiSplashAd.setOnlySupportPlatform(ADSuyiDemoConstant.SPLASH_AD_ONLY_SUPPORT_PLATFORM);
        // 设置开屏广告监听
        adSuyiSplashAd.setListener(new ADSuyiSplashAdListener() {

            @Override
            public void onADTick(long millisUntilFinished) {
                // 如果没有设置自定义跳过按钮不会回调该方法
                Log.d(ADSuyiDemoConstant.TAG, "倒计时剩余时长" + millisUntilFinished);
            }

            @Override
            public void onReward(ADSuyiAdInfo adSuyiAdInfo) {

            }

            @Override
            public void onAdSkip(ADSuyiAdInfo adSuyiAdInfo) {
                Log.d(ADSuyiDemoConstant.TAG, "广告跳过回调，不一定准确，埋点数据仅供参考... ");
            }

            @Override
            public void onAdReceive(ADSuyiAdInfo adSuyiAdInfo) {
                Log.d(ADSuyiDemoConstant.TAG, "广告获取成功回调... ");
                adInstanceManager.onAdReceive(
                        adInstanceManager.adForId(adId),
                        adSuyiAdInfo.getPlatform(),
                        adSuyiAdInfo.getEcpmPrecision(),
                        adSuyiAdInfo.getECPM()
                );
            }

            @Override
            public void onAdExpose(ADSuyiAdInfo adSuyiAdInfo) {
                Log.d(ADSuyiDemoConstant.TAG, "广告展示回调，有展示回调不一定是有效曝光，如网络等情况导致上报失败");
                adInstanceManager.onAdExpose(
                        adInstanceManager.adForId(adId),
                        adSuyiAdInfo.getPlatform(),
                        adSuyiAdInfo.getEcpmPrecision(),
                        adSuyiAdInfo.getECPM()
                );
            }

            @Override
            public void onAdClick(ADSuyiAdInfo adSuyiAdInfo) {
                Log.d(ADSuyiDemoConstant.TAG, "广告点击回调，有点击回调不一定是有效点击，如网络等情况导致上报失败");
                adInstanceManager.onAdClick(
                        adInstanceManager.adForId(adId),
                        adSuyiAdInfo.getPlatform(),
                        adSuyiAdInfo.getEcpmPrecision(),
                        adSuyiAdInfo.getECPM()
                );
            }

            @Override
            public void onAdClose(ADSuyiAdInfo adSuyiAdInfo) {
                Log.d(ADSuyiDemoConstant.TAG, "广告关闭回调，需要在此进行页面跳转");
                adInstanceManager.onAdClose(
                        adInstanceManager.adForId(adId),
                        adSuyiAdInfo.getPlatform(),
                        adSuyiAdInfo.getEcpmPrecision(),
                        adSuyiAdInfo.getECPM()
                );
                jumpMain();
            }

            @Override
            public void onAdFailed(ADSuyiError adSuyiError) {
                if (adSuyiError != null) {
                    String failedJson = adSuyiError.toString();
                    Log.d(ADSuyiDemoConstant.TAG, "onAdFailed----->" + failedJson);
                    adInstanceManager.onAdFailed(adInstanceManager.adForId(adId), adSuyiError);
                }
                jumpMain();
            }
        });

        boolean isApplyPermission = SPUtil.getBoolean(SplashAdActivity.this, "IS_APPLY_PERMISSION", false);

        if (!permissionList.isEmpty() && !isApplyPermission && isApplyPermission) {
            // 存在未申请的权限则先申请
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[0]), REQUEST_CODE);
        } else {
            // 加载开屏广告，参数为广告位ID，同一个ADSuyiSplashAd只有一次loadAd有效
            adSuyiSplashAd.loadAd(adPosId);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (!isRepeatApplyPermission) {
            SPUtil.putBoolean(SplashAdActivity.this, "IS_APPLY_PERMISSION", true);
        }
        if (REQUEST_CODE == requestCode) {
            // 加载开屏广告，参数为广告位ID，同一个ADSuyiSplashAd只有一次loadAd有效
            adSuyiSplashAd.loadAd(adPosId);
        }
    }

    @Override
    public void onBackPressed() {
        // 取消返回事件，增加开屏曝光率
    }

    /**
     * 跳转到主界面
     */
    private void jumpMain() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // TODO 可能需要释放adInstanceManager中的开屏广告 自测的时候需要看一下
    }
}
